package com.qf.mvc2203.controller;

import com.sun.deploy.net.HttpRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/download")
public class DownloadController {
    @Value("${uploadpath}")
    private String filepath;

    /*
     * 文件下载接口，返回值为void
     * */
    @RequestMapping("/test1")
    public void test1(String name, HttpServletResponse response) throws IOException {
        //1.根据传入的文件名找到要下载的文件
        String finaFilepath = filepath + name;
        IOUtils.copy(new FileInputStream(finaFilepath), response.getOutputStream());
    }

    /*
     * 从webapp发布目录下的img目录中下载文件
     * 采用servletContext的方法，把发布目录下的img的相对路径转成绝对路径
     * */
    @RequestMapping("/test2")
    public void test2(String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取文件存放的路径
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/img");
        String finaFileName = realPath + File.separator+ name;

        IOUtils.copy(new FileInputStream(finaFileName), response.getOutputStream());
    }
}
